package com.creative.interceptor;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.creative.constant.Constants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.creative.constant.Constants.LOGIN_TOKEN;
import static com.creative.constant.HttpStatus.UNAUTHORIZED;

public class RefreshTokenInterceptor implements HandlerInterceptor {

    public static final Log logger = LogFactory.get();
    private StringRedisTemplate stringRedisTemplate;

    //    未被注册到spring容器，用构造器注入
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

//        获取请求头内容
//        Enumeration<String> headerNames = request.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            String headerValue = request.getHeader(headerName);
//            logger.info("请求头：{}，值为：{}", headerName, headerValue);
//        }

        // 1.获取请求头的token（前端）
        String WebTokenInfo = request.getHeader("satoken");

        if (StrUtil.isBlank(WebTokenInfo)) {
            logger.info("请求中token不存在");
//            不存在，则拦截，返回401状态码
            response.setStatus(UNAUTHORIZED);
//            拦截
            return false;
        }
        // 2.获取用户信息(satoken)
// 获取当前 Token 的 Token-Session 对象
        SaTokenInfo ServerTokenInfo = StpUtil.getTokenInfo();
//        判断是否存在用户token信息，以此来判定用户的token是否过期
        if (ServerTokenInfo == null) {
            logger.info("用户登录信息过期");
//            不存在，则拦截，返回401状态码
            response.setStatus(UNAUTHORIZED);
//            拦截
            return false;
        }
        if (!Objects.equals(ServerTokenInfo.tokenValue, WebTokenInfo)) {
            logger.info("前端token与session中的token不一致");
            //            不相等，则拦截，返回401状态码
            response.setStatus(UNAUTHORIZED);
//            拦截
            return false;
        }

//        用户的id
        String uid = stringRedisTemplate.opsForValue().get(LOGIN_TOKEN + WebTokenInfo);
        //3.判断用户是否登录
        if (StrUtil.isEmpty(uid)) {
            logger.info("redis中token不存在");
//            刷新一下用户在redis中的信息
            StpUtil.getSession().update();
//            拦截
            return false;
        }

//        刷新redis中token有效期
        stringRedisTemplate.expire(Constants.LOGIN_TOKEN + WebTokenInfo, Constants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        stringRedisTemplate.expire(Constants.LOGIN_SESSION + uid, Constants.LOGIN_USER_TTL, TimeUnit.SECONDS);
//       token续签
        StpUtil.checkLogin();

        return true;
    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        //移除用户
//        UserHolder.removeUser();
//    }


}
